package com.xiaotao.util;

public class GeoUtil {

    private static final double EARTH_RADIUS = 6371; // 地球半径，单位公里

    /**
     * 计算两个坐标点之间的距离（单位：公里）
     */
    public static double calculateDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = Math.toRadians(lat1);
        double radLat2 = Math.toRadians(lat2);
        double a = radLat1 - radLat2;
        double b = Math.toRadians(lng1) - Math.toRadians(lng2);

        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 1000) / 1000.0;
        return s;
    }

    /**
     * 判断两个坐标点是否在指定距离内
     */
    public static boolean isWithinDistance(double lat1, double lng1, double lat2, double lng2, double maxDistance) {
        double distance = calculateDistance(lat1, lng1, lat2, lng2);
        return distance <= maxDistance;
    }
}